//
//  MapViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/4/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "MapViewController.h"
#import "GruphotoAppDelegate.h"
#import "GruphotoTabBarController.h"
#import "EventDetailViewController.h"
#import "CustomCallout/EventSmallAnnotation.h"
#import "Event.h"

@interface MapViewController ()
- (void)addMapAnnotations;
@end

@implementation MapViewController
@synthesize listMapView, mapMode;
@synthesize mapSearchBar, events;

#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization        
        UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [listButton setBounds:CGRectMake(0, 0, 51, 30)];
        [listButton setBackgroundImage:[UIImage imageNamed:@"button_list.png"] forState:UIControlStateNormal];
        [listButton addTarget:self action:@selector(listButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *listButtonItem = [[UIBarButtonItem alloc] initWithCustomView:listButton];
        self.navigationItem.rightBarButtonItem = listButtonItem;
        [listButtonItem release];
        self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    for (UIView *subview in listMapView.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            subview.hidden = YES;
            break;
        }
    }
    
    mapSearchBar.backgroundImage = [UIImage imageNamed:@"background_searchbar.png"];
    if (mapMode == EventMapModeNormal) {
        mapSearchBar.hidden = YES;
        CGRect mapRect = CGRectMake(0, 0, 320, [Global screenHeight]);
        listMapView.frame = mapRect;
    }
    
    [self addMapAnnotations];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    GruphotoTabBarController *tabBarController = (GruphotoTabBarController *)self.tabBarController;
    [tabBarController hidesFakeTabBar:NO];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.listMapView = nil;
    mapSearchBar.delegate = nil;
    self.mapSearchBar = nil;
}

- (void)dealloc {
    [annotations release];
    [listMapView release];
    mapSearchBar.delegate = nil;
    [mapSearchBar release];
    self.events = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods
- (void)addMapAnnotations {
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Loading..."];
    [listMapView removeAnnotations:listMapView.annotations];
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance([GruphotoAppDelegate sharedDelegate].currentLocation.coordinate, 120, 120);
    MKCoordinateRegion adjustedRegion = [listMapView regionThatFits:viewRegion];
    [listMapView setRegion:adjustedRegion animated:YES];
    
    for (int i = 0; i < events.count; i++) {
        Event *event = [events objectAtIndex:i];
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([event.latitude doubleValue], [event.longitude doubleValue]);
        EventSmallAnnotation *pinAnnotation = [[EventSmallAnnotation alloc] initWithCoordinate:coord];
        pinAnnotation.event = event;
        pinAnnotation.mapView = listMapView;
        pinAnnotation.navigationController = self.navigationController;
        [listMapView addAnnotation:pinAnnotation];
        [pinAnnotation release];
        if (i == events.count - 1) {
            [[GruphotoAppDelegate sharedDelegate] hideHUD];
        }
    }
}

#pragma mark - Action methods
- (IBAction)listButtonPressed:(id)sender {
    GruphotoTabBarController *tabBarController = (GruphotoTabBarController *)self.tabBarController;
    [UIView animateWithDuration:0.2 animations:^{
        [tabBarController showFakeTabBar:YES];
    } completion:^(BOOL finished) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self addMapAnnotations];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}

#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if([annotation conformsToProtocol:@protocol(AnnotationDelegate)]) {
        NSLog(@"First step");
        return [((NSObject<AnnotationDelegate>*)annotation) annotationViewInMap:mapView];
    }
    else {
        return [mapView viewForAnnotation:mapView.userLocation];
    }
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    MKAnnotationView *annotationView;
    for (annotationView in views) {
        if (![annotationView isKindOfClass:[EventCalloutView class]]) {
            CGRect endFrame = annotationView.frame;
            annotationView.frame = CGRectMake(annotationView.frame.origin.x, annotationView.frame.origin.y - 230.0, annotationView.frame.size.width, annotationView.frame.size.height);
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.45];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            [annotationView setFrame:endFrame];
            [UIView commitAnimations];
        }
    }
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if([view conformsToProtocol:@protocol(CustomAnnotationViewProtocol)]) {
        [((NSObject<CustomAnnotationViewProtocol>*)view) didSelectAnnotationViewInMap:mapView];
    }
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    if([view conformsToProtocol:@protocol(CustomAnnotationViewProtocol)]) {
        [((NSObject<CustomAnnotationViewProtocol>*)view) didDeselectAnnotationViewInMap:mapView];
    }
}

@end
